package com.csw.android.androidtest.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;

import androidx.annotation.Nullable;

/**
 * 由于默认的radioButton设置图片缩放异常，各机型之间也存在差异，这里通过修改setCompoundDrawables对图片尺寸进行调整
 */
public class HomeRadioButton extends androidx.appcompat.widget.AppCompatRadioButton {
    public HomeRadioButton(Context context) {
        super(context);
    }

    public HomeRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 我们通过xml文件drawableTop属性添加的图标，通过查看源码，发现其父类TextView中的初始化读取了该属性生成drawable,并对drawable进行边界设置
     * 最终调用setCompoundDrawables设置已经准备好尺寸的drawable对象
     * public void setCompoundDrawablesWithIntrinsicBounds(@Nullable Drawable left,
     *         @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) {
     *     if (left != null) {
     *         left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
     *     }
     *     if (right != null) {
     *         right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight());
     *     }
     *     if (top != null) {
     *         top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
     *     }
     *     if (bottom != null) {
     *         bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight());
     *     }
     *     setCompoundDrawables(left, top, right, bottom);
     * }
     */
    public HomeRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 这里修改setCompoundDrawables方法，对drawableTop重新进行图片尺寸设置
     */
    @Override
    public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) {
        if (top != null) {
            int dp40 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
            top.setBounds(0, 0, dp40, dp40);
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }
}
